
// Get Druggy estimate
function DruggyAPEstimate(amount)
{
	// Get estimate
	var zeroDrugTime = Number(localStorage.getItem ('po_druggy_zeroDrugTime'));
	var drugTickTime = Number(localStorage.getItem ('po_druggy_tick')) * 1000;
	var TCval = Number(localStorage.getItem ('po_druggy_TCval'));
	var totAPs = 0;
	var curtime = new Date();
	var curtimeSec = curtime.getTime();	

	// Here's the plan.  Create a function based on time till 0 drug -> AP
	// go through function for each drug to be taken (amount) and get AP's
	// for each, with a final total.  Put in some boundaries. <1, >27
	// equation for drug 1->22 = -7.62*#drugs + 242.62
	// equation for drugs 23->27 = -13.33*#drugs + 366.66
	// assume 0 APs for anything > 27 druggyness.
	
	// get overdrug from time left based on tick.
	var overdrug = ((zeroDrugTime - curtimeSec) / drugTickTime);
	
	if (overdrug < 0) overdrug = 0.0;
	if (TCval < 0) TCval = 0;
	
	// loop for each drug to get total APs
	for (i = 0;(i < amount);i++)
	{
		overdrug = overdrug + 1;
		if ((overdrug-TCval)<1)
		{
			totAPs = totAPs + 235;
		}
		else if ((overdrug-TCval) < 23)
		{
			totAPs = totAPs + (-7.62*(overdrug-TCval) + 242.62);
		}
		else if ((overdrug-TCval) < 27)
		{
			totAPs = totAPs + (-13.33*(overdrug-TCval) + 366.66);
		}
		else
		{
			break;
		}
	}

	return(parseInt(totAPs+0.5));
}


// Capture Druggy event
function checkkey(event) {

	var resid = event.target.parentElement.resid;
	var amount = event.target.parentElement.amount;

	if (resid == null)
	{
		// building and pvnpc...
		resid = event.target.parentElement.parentElement.previousSibling.resid;
		amount = event.target.parentElement.parentElement.previousSibling.amount;
	}
	
	if (resid.value == '51')
	{
		var APestimate = DruggyAPEstimate(amount.value);
		var APpert = 0;

		if (Number(amount.value) > 0) APpert = parseInt(APestimate/amount.value);
		
		if (event.target.parentElement.lastChild.type == 'submit')
		{
			var mybr = document.createElement('br');
			var mytext = document.createTextNode('AP estimate:' + APestimate + ' (' + APpert + '/t)');
			event.target.parentElement.appendChild(mybr);
			event.target.parentElement.appendChild(mytext);
		}
		else
		{
			event.target.parentElement.lastChild.nodeValue = 'AP estimate:' + APestimate  + ' (' + APpert + '/t)';
		}
	}
		
}

window.addEventListener('keyup', checkkey, true);